import indexedDB from "./indexedDB";
type promiseCb = (value: any) => void
export const getBookContent = (bookKey: string) => {
    const getContentFn = async (resolve: promiseCb, reject: promiseCb) => {
        let books = await indexedDB.get('books')
        if (books && Array.isArray(books)) {
            const file = books.find(item => item.key == bookKey)
            let bookContent = await indexedDB.get(bookKey)
            if (bookContent && file) {
                let fileType = ''
                const fileFormat = file.format
                switch (fileFormat) {
                    case 'PDF':
                        fileType = 'application/pdf'; break
                    case 'TXT':
                        fileType = 'text/plain'; break
                }
                const blob = new Blob([bookContent as ArrayBuffer], { type: fileType });
                // 读取Blob为文本或base64格式的URL
                const textReader = new FileReader();
                textReader.onload = function (e) {
                    resolve((e.target as any).result)

                };
                textReader.onerror = function (e) {
                    reject(e)
                }
                if (fileFormat == 'TXT') {
                    textReader.readAsText(blob); // 默认UTF-8编码
                } else if (fileFormat == 'PDF') {
                    textReader.readAsDataURL(blob);
                }

            } else {
                reject('暂未获取到内容~')
            }
        } else {
            reject('暂未获取到图书~')
        }
    }
    return new Promise((resolve, reject) => {
        getContentFn(resolve, reject)
    })

}